/* Copyright (c) 2007 Scott Lembcke
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "chipmunk.h"

cpBitmaskShape *
cpBitmaskShapeAlloc(void)
{
	//printf("pointAlloc\n");
	return (cpBitmaskShape *)calloc(1, sizeof(cpBitmaskShape));
}

 
static cpBB
cpBitmaskShapeCacheData(cpShape *shape, cpVect p, cpVect rot)
{
	printf("pointCacheData\n");
	cpBitmaskShape *cb = (cpBitmaskShape *)shape;
	
	//TODO considerare rotazione

	printf("L: %f B: %f R: %f T: %f\n",p.x, p.y, p.x+(cpFloat)cb->mask->w, p.y+(cpFloat)cb->mask->h);
	
	return cpBBNew(p.x, p.y, p.x+(cpFloat)cb->mask->w, p.y+(cpFloat)cb->mask->h);
}

static void
cpBitmaskShapeDestroy(cpShape *shape)
{
	printf("pointDest\n");
	cpBitmaskShape *cb = (cpBitmaskShape *)shape;
	bitmask_free(cb->mask);
}

static int
cpBitmaskShapePointQuery(cpShape *shape, cpVect pos){
	printf("pointQuery\n");
	cpBitmaskShape *cb = (cpBitmaskShape *)shape;
	cb->p=pos;

	//TODO considerare rotazione
	return bitmask_getbit(cb->mask, ((int)pos.x)%cb->mask->w,((int)pos.y)%cb->mask->h);
}

static const cpShapeClass bitmaskClass = {
	CP_BITMASK_SHAPE,
	cpBitmaskShapeCacheData,
	cpBitmaskShapeDestroy,
	cpBitmaskShapePointQuery,
};

cpBitmaskShape *
cpBitmaskShapeInit(cpBitmaskShape *bitM, cpBody *body, bitmask_t *bitmask,cpVect offset)
{	
	printf("pointInit\n");
	bitM->tVerts=offset;
	bitM->mask=bitmask;
	cpShapeInit((cpShape *)bitM, &bitmaskClass, body);

	return bitM;
}

cpShape *
cpBitmaskShapeNew(cpBody *body, bitmask_t *bitmask, cpVect offset)
{
	printf("pointNew\n");
	return (cpShape *)cpBitmaskShapeInit(cpBitmaskShapeAlloc(), body, bitmask, offset);
}
